package t.yatush.core_infra_svc;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class ScriptHistoryRetriever extends DbSysTool{

	private static ScriptHistoryRetriever instance;

	public static ScriptHistoryRetriever getInstance(){
		if(instance == null){
			instance = new ScriptHistoryRetriever();
		}
		return instance;
	}

	private ScriptHistoryRetriever() {
		super();
	}

	public Set<String> getScriptsHistory(){
		try {
			Set<String>  resultSet = new HashSet<String>();
			Statement st = con.createStatement();
			ResultSet rs = st.executeQuery("SELECT * FROM sys_scripts_doc");
			while (rs.next()) {
				resultSet.add(rs.getString(2));
			}
			rs.close();
			st.close();
			return resultSet;
		} catch (SQLException e) {
			System.out.println("sys_scripts_doc does not exist!!");
			return null;
		}
	}

	public void createScriptDocTable(){
		PreparedStatement statement;
		try {
			statement = con.prepareStatement("create table sys_scripts_doc(date timestamp, name varchar(255));");
			statement.execute();
			statement.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static class ScriptHistory{

		private String name;
		private int size;

		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public int getSize() {
			return size;
		}
		public void setSize(int size) {
			this.size = size;
		}


	}

	public void insertHistoryChanges(List<String> newScriptsHistory) throws Exception {
		if(newScriptsHistory != null && newScriptsHistory.size() > 0 ){
			String insertStr = "insert into sys_scripts_doc(name) values ";
			for(Iterator<String> it = newScriptsHistory.iterator();it.hasNext();){
				String fileName = it.next();
				insertStr+="('"+fileName+"')";
				if(it.hasNext()){
					insertStr+=",";
				}
			}
			insertStr+=";\n commit;";
			runStrScript(insertStr);
		}
	}

	public void updateHistoryChanges(Map<String, Integer> updatedScriptsHistory) throws Exception {
		if(updatedScriptsHistory!=null && updatedScriptsHistory.size() > 0){
			String updateStr = "";
			for(Entry<String, Integer> entry:updatedScriptsHistory.entrySet()){
				updateStr+= "update sys_scripts_doc set set size="+entry.getValue()+" where name = '"+entry.getKey()+"';\n";
			}
			updateStr+="commit;";
			runStrScript(updateStr);
		}

	}

}
